package org.yysd.widget;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CloseableTabComponent extends JPanel {
    private JTabbedPane tabbedPane;
    private int tabIndex;

    public CloseableTabComponent(JTabbedPane tabbedPane, int tabIndex) {
        super(new FlowLayout(FlowLayout.LEFT, 0, 0));
        this.tabbedPane = tabbedPane;
        this.tabIndex = tabIndex;

        setOpaque(false);

        JLabel label = new JLabel(tabbedPane.getTitleAt(tabIndex));
        add(label);

        JButton closeButton = new JButton("x");
        closeButton.setBorderPainted(false);
        closeButton.setContentAreaFilled(false);
        closeButton.setFocusable(false);
        closeButton.setForeground(Color.RED);

        // Add action listener to close the tab when the close button is clicked
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tabbedPane.removeTabAt(CloseableTabComponent.this.tabIndex);
            }
        });

        add(closeButton);
    }
}
